<template>
    <div>
        <el-button type="primary" @click="handleEdit">新增</el-button>
        <!-- <el-input v-for="(condition, index) in query.SearchConditions" v-model="condition.Value" :key="index"
            style="width: 240px" clearable :placeholder="'Please input ' + condition.FieldName" />
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button type="primary" @click="clearQuery">重置</el-button> -->
    </div>
    <el-table v-loading="isLoading" height="800px" :show-overflow-tooltip="true" :data="tableData">
        <!-- <el-table-column v-for="item in bgcolumnNames" :prop="item.Name" :label="item.label" /> -->
        <el-table-column v-for="item in bgcolumnNames" :key="item.Name" :prop="item.Name" :label="item.Label">
            <template #default="{ row }">
                <!-- {{ row }} -->
                <span v-if="item.ControlType === 7">{{ item.EnumDic[row[item.Name]] }}</span>
                <span v-else>{{ row[item.Name] }}</span>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
                <el-button link type="primary" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row)">
                    <template #reference>
                        <el-button link type="danger" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible" title="编辑">
        <el-form @submit.native.prevent v-for=" item in bgcolumnNames" :model="editItem">
            <el-form-item v-if="item.IsEditable" :label="item.Label" :label-width="formLabelWidth">
                <JSCodeMirror v-if="item.ControlType == 1" v-model:value="editItem[item.Name]"></JSCodeMirror>
                <el-select @change="handleChange(item)" v-else-if="item.ControlType == 7" v-model="editItem[item.Name]"
                    placeholder="请选择">
                    <el-option v-for="(label, value) in item.EnumDic" :label="label" :value="Number(value)" />
                </el-select>
                <el-input v-else v-model="editItem[item.Name]" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="onTestConnect">测试连接</el-button>

                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="onConfirm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, nextTick, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import JSCodeMirror from '../components/JSCodeMirror.vue'; // 引入 CodeEditor 组件
import api from '../api'
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

var columns = reactive({})
const query = reactive({
    pageIndex: 1,
    pageSize: 30,
    SearchConditions: []
})
var isLoading = ref(true)
// var label=['']
var tableData = ref([])
var editItem = reactive({
    EDBType: 0,
    ConnectStr: ''
});

const onTestConnect = () => {

    api.post('DBConfig/TestConnect', editItem).then(res => {

        if (res.Code == 200) {
            ElMessage.success('连接成功')
        }

    })
}
const handleChange = (item) => {
    console.log('change', item, editItem)
    editItem.ConnectStr = getConnStrByDBType(item.EnumDic[editItem.EDBType])
    // console.log(str)
}
const clearQuery = async () => {
    query.pageIndex = 1 // 重置页码
    query.pageSize = 30 // 重置每页条数
    query.SearchConditions.forEach(condition => {
        condition.Value = ''
    })
}
// 定义方法
const getDataList = async () => {
    // var postData = {
    //     pageIndex: 1,
    //     pageSize: 30,
    // }
    isLoading.value = true
    var res = await api.post('DBConfig/List', query)
    isLoading.value = false
    var data = res.Data
    tableData.value = data.list
    // bgcolumnNames = data.columnNames
    console.log(data.columnNames);
};

var bgcolumnNames = [
    {
        "Name": "Id",
        "Order": 1,
        "Label": "Id",
        "ControlType": 3,
        "TypeName": "Int32",
        "IsShow": true,
        "IsEditable": false,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "Name",
        "Order": 100,
        "Label": "Name",
        "ControlType": 3,
        "TypeName": "String",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": true,
        "EnumDic": null
    },
    {
        "Name": "EDBType",
        "Order": 100,
        "Label": "数据库类型",
        "ControlType": 7,
        "TypeName": "DbType",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": false,
        "EnumDic": {
            "0": "MySql",
            "1": "SqlServer",
            "2": "Sqlite",
            "3": "Oracle",
            "4": "PostgreSQL",
            "5": "Dm",
            "6": "Kdbndp",
            "7": "Oscar",
            "8": "MySqlConnector",
            "9": "Access",
            "10": "OpenGauss",
            "11": "QuestDB",
            "12": "HG",
            "13": "ClickHouse",
            "14": "GBase",
            "15": "Odbc",
            "16": "OceanBaseForOracle",
            "17": "TDengine",
            "18": "GaussDB",
            "19": "OceanBase",
            "20": "Tidb",
            "21": "Vastbase",
            "22": "PolarDB",
            "23": "Doris",
            "900": "Custom"
        }
    },
    {
        "Name": "ConnectStr",
        "Order": 100,
        "Label": "连接字符串",
        "ControlType": 3,
        "TypeName": "String",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": true,
        "EnumDic": null
    },
    {
        "Name": "CreateTime",
        "Order": 100,
        "Label": "创建时间",
        "ControlType": 5,
        "TypeName": "DateTime",
        "IsShow": true,
        "IsEditable": false,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "UpdateTime",
        "Order": 100,
        "Label": "更新时间",
        "ControlType": 5,
        "TypeName": "Nullable`1",
        "IsShow": true,
        "IsEditable": false,
        "IsNullable": true,
        "EnumDic": null
    }
]
/**
 * 传入数据库类型，获取该类型数据库的连接字符串
 * @param dbType 数据库类型
 */
const getConnStrByDBType = (dbType) => {
    let ConnStr = "";
    switch (dbType) {
        case "MySql":
        // Server=localhost;Database=testdb;UserId=root;Password=123456;
            ConnStr = "Server=localhost;Database=?;UserId=?;Password=?;"
            break;
        case "SqlServer":
            ConnStr = "Server=?;Database=?;UserId=?;Password=?;"
            break;
        case "Sqlite":
            break;
        case "Oracle":
            break;
        case "PostgreSQL":
            break;
        default:
            ConnStr = "暂时未提供该数据库的连接字符串示例"
            break;
    }
    return ConnStr;
}

/**
 * 确认并更新模板信息
 * 无参数
 * 无明确返回值，但会通过控制台输出和界面提示更新结果
 */
const onConfirm = async () => {
    // 提交编辑中的模板信息至服务器

    var res = await api.post('DBConfig/Update', editItem)

    // 根据服务器返回代码判断操作成功与否
    if (res.Code == 200) {
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: res.Message,
            type: 'success',
        })
        getDataList()
        // 关闭当前对话框
        dialogFormVisible.value = false
    }
}
const handleDelete = async item => {

    item.isDeleted = true
    var res = await api.post('DBConfig/Update', item)
    if (res.Code == 200) {
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: "删除成功",
            type: 'success',
        })
        getDataList()
    }
}

const handleEdit = async (item) => {

    editItem = reactive(JSON.parse(JSON.stringify(item)));
    dialogFormVisible.value = true
}

onMounted(async () => {
    try {

        getDataList()

        // const data = await $api.get('/your-api-endpoint');
        // 使用获取的数据
    } catch (error) {

    }
});


</script>

<style>
.el-input {
    margin: 0 5px;
}

.CodeMirror {
    margin-right: 100px;
}

.CodeMirror-sizer {
    min-width: 500px !important;
}

.el-dialog__body {
    overflow: auto;
    max-height: 500px;
}
</style>